from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtMultimedia import *
import urllib
from urllib import parse
from qt_material import apply_stylesheet

import sys


class myPet(QWidget):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self)
        self.initUI()

    def initUI(self):
        self.action = 0
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.SubWindow)
        self.setAutoFillBackground(False)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.repaint()
        self.img = QLabel(self)
        self.actionDatas = []
        self.initData()
        self.index = 0
        self.setPic('pig1.0.png')
        self.resize(310, 266)
        self.runing = False

        self.timer = QTimer()
        self.timer.timeout.connect(self.actionRun)
        self.timer.start(150)  # 毫秒为单位，动画频率

        self.timeToInit = QTimer()
        self.timeToInit.setSingleShot(True)
        self.timeToInit.timeout.connect(self.initPos)

        self.listView_Anim = QPropertyAnimation(self, b'geometry')
        self.listView_Anim.setDuration(5000)  # 设定动画时间
        self.listView_Anim.setEndValue(QRect(-266, -266, 266, 266))  # 设置终止大小 QRect可以用一组左、顶、宽和高整数来构造

        self.player = QMediaPlayer()
        self.player.setVolume(100)
        self.playlist = QMediaPlaylist()
        self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile('music/clockMusic.mp3')))
        self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile('music/running.mp3')))
        self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
        self.player.setPlaylist(self.playlist)

        self.move(QDesktopWidget().screenGeometry().width() - 300, QDesktopWidget().screenGeometry().height() - 300)

    def getImgs(self, pics):
        listPic = []
        for item in pics:
            img = QImage()
            img.load('img/' + item)
            listPic.append(img)
        return listPic

    def initData(self):
        imgs = self.getImgs(['pig2.0.png', 'pig3.0.png'])
        self.actionDatas.append(imgs)
        imgs = self.getImgs(['pig1.0.png', 'pig4.0.png'])
        self.actionDatas.append(imgs)

    def actionRun(self):
        if not self.runing:
            self.index = 0
            self.runing = True
        self.runFunc(self.actionDatas[self.action])

    def setPic(self, pic):
        img = QImage()
        img.load('img/' + pic)
        self.img.setPixmap(QPixmap.fromImage(img))

    def runFunc(self, imgs):
        if self.index >= len(imgs):
            self.index = 0
            self.runing = False
        self.img.setPixmap(QPixmap.fromImage(imgs[self.index]))
        self.index += 1

    # 初始化玩偶状态
    def initPos(self):
        self.hide()
        screen = QDesktopWidget().screenGeometry()
        self.move(screen.width() - 300, screen.height() - 300)
        self.player.pause()
        self.action = 0
        self.playlist.setCurrentIndex(self.action)

    def clockPlayer(self):
        self.player.play()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.m_drag = True
            self.m_DragPosition = event.globalPos() - self.pos()
            event.accept()
            self.setCursor(QCursor(Qt.OpenHandCursor))

    def mouseMoveEvent(self, QMouseEvent):
        if Qt.LeftButton and self.m_drag:
            self.move(QMouseEvent.globalPos() - self.m_DragPosition)
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_drag = False
        self.setCursor(QCursor(Qt.ArrowCursor))

    def keyPressEvent(self, QKeyEvent):
        if QKeyEvent.key() == Qt.Key_Escape:
            print('按下了Esc键')
            # self.itsTimeToGo()

    def itsTimeToGo(self):
        if self.action == 0:
            self.action = 1
        self.listView_Anim.start()  # 动画开始
        # 切歌
        self.playlist.setCurrentIndex(self.action)
        self.timeToInit.start(5200)


class QInputDialogDemo(QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        super(QInputDialogDemo, self).__init__()
        self.initUI()
        self.initMenu()

        self.timer = QTimer()
        self.timer.setSingleShot(True)  # 单次触发
        self.timer.timeout.connect(self.trayIcon.show)  # 关闭闹钟后显示托盘内图标

        self.current_timer_lis = QTimer()
        self.current_timer_lis.timeout.connect(self.timing_lis)

        self.timeToEscape = QTimer()
        self.timeToEscape.setSingleShot(True)
        self.timeToEscape.timeout.connect(self.autoEscape)

        self.timerToLoop = QTimer()
        self.timerToLoop.setSingleShot(True)  # 单次触发
        self.timerToLoop.timeout.connect(self.start_btn_click)


    def initUI(self):
        self.setWindowTitle(urllib.parse.unquote("%E6%9B%BE%E6%96%B0%E8%8C%B9%E7%9A%84%E5%B0%8F%E9%97%B9%E9%92%9F"))
        self.setWindowIcon(QIcon('img/pig1.0.png'))  # 设置应用图标
        self.setWindowFlags(Qt.MSWindowsFixedSizeDialogHint | Qt.Dialog)

        # 表单
        self.form = QFormLayout()  # 初始化一个表单布局

        self.current_date_label = QLabel()
        self.current_date_label.setText("当前时间：")
        self.current_date_label_time = QLabel()
        self.current_date_label_time.setText(QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm:ss dddd'))
        self.current_timer = QTimer()
        self.current_timer.timeout.connect(self.show_current)
        self.current_timer.start(1000)

        self.timing_date_label = QLabel()
        self.timing_date_label.setText("定时时间：")
        self.timing_date_time = QDateTimeEdit()
        self.timing_date_time.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
        self.timing_date_time.setDateTime(QDateTime.currentDateTime())

        self.set_rightone_label = QLabel()
        self.set_rightone_label.setText("添加闹钟(分)：")
        self.set_rightone_box = QComboBox()
        self.set_rightone_box.addItems(["60", "45", "30", "15", "10"])

        self.loopFlag = 1
        self.loopCheckBox = QCheckBox()
        self.loopCheckBox.setChecked(True)  # 默认选中
        self.loopCheckBox.setText("重复")
        self.loopCheckBox.stateChanged.connect(self.loopClock)

        self.clockDetailLabel = QLabel()
        self.clockDetailLabel.setText("已有闹钟：")

        self.clockDetail = QLabel()
        self.clockDetail.setText('暂无闹钟，设置一个吧~')

        self.form.addRow(self.current_date_label, self.current_date_label_time)
        # self.form.addRow(self.timing_date_label, self.timing_date_time)
        self.form.addRow(self.set_rightone_label, self.set_rightone_box)
        self.form.addRow(self.clockDetailLabel, self.clockDetail)

        # 布局
        self.hbox = QHBoxLayout()  # 初始化水平布局
        self.version = QLabel()
        self.version.setText(urllib.parse.unquote("%E6%96%B0%E8%8C%B9%E4%BC%98%E9%80%89%E5%80%BE%E6%83%85%E8%B5%9E%E5%8A%A9"))

        self.start_btn = QPushButton()
        self.start_btn.setText("添加闹钟")
        self.start_btn.setStyleSheet("color:rgb(255,255,255,255);font-size:16px;font-family:YouYuan;")
        self.start_btn.clicked.connect(self.start_btn_click)

        self.hbox.addWidget(self.version)
        self.hbox.addWidget(self.start_btn)
        self.hbox.addWidget(self.loopCheckBox)

        self.vbox = QVBoxLayout()  # 初始化垂直布局
        self.vbox.addLayout(self.form)
        self.vbox.addLayout(self.hbox)

        self.setLayout(self.vbox)  # 设置主布局

    def initMenu(self):
        quit = QAction("退出", self, triggered=self.close)
        quit.setIcon(QIcon("img/pig1.0.png"))
        clock = QAction("打开闹钟", self, triggered = openClock)
        clock.setIcon(QIcon("img/pig1.0.png"))
        self.trayIconMenu = QMenu(self)
        self.trayIconMenu.addAction(clock)
        self.trayIconMenu.addAction(quit)
        self.trayIcon = QSystemTrayIcon(self)
        self.trayIcon.setIcon(QIcon("img/pig1.0.png"))
        self.trayIcon.setContextMenu(self.trayIconMenu)
        self.trayIcon.activated[QtWidgets.QSystemTrayIcon.ActivationReason].connect(self.openMainWindow)

    def show_current(self):
        # 刷新当前时间显示、每隔一秒钟刷新
        current_time = QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm:ss dddd')
        self.current_date_label_time.setText(current_time)

    def start_btn_click(self):
        self.start_btn.setText("Success")
        QTimer.singleShot(1000, self.changeBtnText)

        self.current_timer_lis.start(1000)
        self.initClock()

    def initClock(self):
        # 计算并添加闹钟
        mins = self.set_rightone_box.currentText()
        self.timing_date_time.setDateTime(QDateTime.currentDateTime().addSecs(int(mins) * 60))
        # 设置12秒后的闹钟 调试用
        # self.timing_date_time.setDateTime(QDateTime.currentDateTime().addSecs(12))
        self.clockDetail.setText(self.timing_date_time.dateTime().toString('yyyy-MM-dd hh:mm:ss dddd'))


    def loopClock(self):
        self.loopFlag = -self.loopFlag
        if self.loopFlag == -1: # 取消连续的同时取消闹钟
            self.current_timer_lis.stop()
            self.clockDetail.setText('暂无闹钟，设置一个吧~')

    def changeBtnText(self):
        self.start_btn.setText("添加闹钟")

    def timing_lis(self):
        if QDateTime.currentDateTime() < self.timing_date_time.dateTime():
            pass
            # print("[{}]:定时时间没有到达".format(QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm:ss dddd')))
        else:
            print("[{}]:响铃！！！".format(QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm:ss dddd')))
            if self.loopFlag == 1:  # 连续设定闹钟
                self.initClock()
            else:
                self.current_timer_lis.stop()
                self.clockDetail.setText('暂无闹钟，设置一个吧~')
            self.showTime()

    def showTime(self):
        pet.show()
        pet.clockPlayer()
        clock.hide()
        self.timeToEscape.start(3000)  # 猪猪自动跑掉的时间
        self.timer.start(6000)

    def autoEscape(self):
        pet.itsTimeToGo()

    # 双击托盘打开闹钟
    def openMainWindow(self, reason):
        if reason == QtWidgets.QSystemTrayIcon.DoubleClick:
            self.trayIcon.setVisible(False)
            clock.show()

    def closeEvent(self, event):
        if self.trayIcon.isVisible():
            self.close()
        else:
            self.hide()
            event.ignore()
            self.trayIcon.show()

def openClock():
    clock.trayIcon.hide()
    clock.show()

if __name__ == '__main__':
    global pet
    global clock
    app = QApplication(sys.argv)
    apply_stylesheet(app, theme='dark_pink.xml')

    clock = QInputDialogDemo()
    pet = myPet()

    clock.show()
    sys.exit(app.exec_())
from PyQt5.QtMultimedia import *